<template>
  <div class="tree-wrapper">
    <div class="mb-10">
      <m-button size="mini" width="auto" @click="handleActionClick('add')">新增</m-button>
      <m-button size="mini" width="auto" @click="handleActionClick('edit')">修改</m-button>
      <m-button size="mini" width="auto" @click="handleActionClick('look')">查看</m-button>
      <m-button size="mini" width="auto" type="danger" @click="handleDel">删除</m-button>
    </div>
    <m-input class="mb-10" v-model="filterText" clearable placeholder="输入关键字进行过滤" />
    <el-tree
      ref="tree"
      :node-key="nodeKey"
      :data="treeData"
      :props="props"
      :filter-node-method="filterNode"
      :highlight-current="highlightCurrent"
      :default-expand-all="defaultExpandAll"
      :expand-on-click-node="expandOnClickNode"
      @node-click="handleNodeClick"
    >
      <span class="el-tree-node__label" slot-scope="{ node }" :title="node.label">{{ node.label }}</span>
    </el-tree>
  </div>
</template>

<script>
export default {
  name: 'MTree',
  props: {
    value: {
      type: String,
      default: () => {},
    },
    nodeKey: {
      type: String,
      default: 'id',
    },
    treeData: {
      type: Array,
      default: () => [],
    },
    props: {
      type: Object,
      default: () => {
        return {
          children: 'children',
          label: 'name',
        }
      },
    },
    highlightCurrent: {
      type: Boolean,
      default: true,
    },
    defaultExpandAll: {
      type: Boolean,
      default: true,
    },
    expandOnClickNode: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      filterText: '',
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data[this.props.label].indexOf(value) !== -1
    },
    resetChecked() {
      this.$refs.tree.setCurrentKey(null)
    },
    handleActionClick(type) {
      this.$emit('action', type)
    },
    handleDel() {
      this.$emit('del')
    },
    handleNodeClick(node) {
      const nodeKey = node[this.nodeKey]
      this.$emit('input', nodeKey)
      this.$emit('change', node)
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep {
  .el-tree {
    font-size: 15px;
    color: #333333;
    font-weight: 500;
    background-color: transparent;
  }
}
.tree-wrapper {
  position: sticky;
  top: 20px;
  max-height: calc(100vh - 110px);
  overflow: auto;
}
</style>
